// pages/game_center/game_center.js
const db = wx.cloud.database();
const _ = db.command
const app = getApp()
let tasks = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_data: {},
    room: {},
    time: '00:00:00',
    h: '00',
    m: '00',
    s:'00',
    setInter: '',
    num: 1,
    start_time: false,
    is_end: '',
    show_message:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let room = {}
    let user_data = {}
    room = app.globalData.room
    user_data = app.globalData.user_data
    this.setData({
      room,
      user_data
    })
    this.get_watch()
  },
  get_watch() {
    let room = this.data.room
    let that = this
    let isok = 0
    let user_data = this.data.user_data
    let show_message = ''
    console.log("1111111",room);
    const watcher = db.collection('room').doc(room._id).watch({
      onChange: (snapshot) => {
        console.log(snapshot);
        if (snapshot.docChanges[0].queueType != 'init') {
          room = snapshot.docs[0]
          user_data = room.users[user_data.color]
          if (room.room_state != undefined && room.room_state == true&&room.winner != user_data.color) {
            show_message = '游戏结束,恭喜'+room.winner+"队胜利！"
            that.setData({
              room,
              is_end: 'Modal',
              show_message
            })
          } else if (room.room_state == undefined || room.room_state == false) {
            that.setData({
              room,
              user_data
            })
          }
        }
      },
      onError:(err=>{console.log(err);})
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  clickbox(e) {
    console.log(e);
    let idx = e.target.dataset.target
    let room = this.data.room
    let user_data = this.data.user_data
    if(user_data.time == undefined) user_data.time = ''
    let h = this.data.h
    let m = this.data.m
    let s = this.data.s
    let time = h+':'+m+':'+s
    console.log("roomddddd", room);
    console.log("user",user_data);
    if (user_data.tasks[idx].color === "white") {
      user_data.tasks[idx].color = user_data.color
      user_data.tasks_num++
      user_data.time = time
      room.users[user_data.color]= user_data
      console.log("roomddddd", room);
      wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'update_tasks',
      // 传给云函数的参数
      data: {
        tasks: room.tasks,
        users:room.users,
        _id: room._id,
       room_state:room.room_state
      },
      // 成功回调
      complete: res => {
        console.log(res)
      }
    })
    
    this.setData({
      room,
      user_data
    })

    }
    

  },
  queryTime() {
    const that = this
    let hou = that.data.h
    let min = that.data.m
    let sec = that.data.s
    that.data.setInter = setInterval(() => {
      sec++
      if (sec >= 60) {
        sec = 0
        min++
        if (min >= 60) {
          min = 0
          hou++
          that.setData({
            h:(hou<10?'0'+min :min)
          })
        } else {
          that.setData({
            m:(min<10?'0'+min :min)
          })
        }
      }else {
        that.setData({
          s:(sec<10?'0'+sec :sec)
        })
      }
      let numval = that.data.num + 1
      that.setData({num:numval})
    }, 1000);
  },
  taskStart() {
    let room = this.data.room
    this.setData({
      start_time:true,
    })
    this.queryTime()
  },
  taskEnd() {
    this.setData({
      start_time:false,
    })
    clearInterval(this.data.setInter)
  },
  onUnload() {
    let that = this
    clearInterval(this.data.setInter)
    
  },
  remake() {
    let room = this.data.room
    wx.cloud.callFunction({
      name: 'remove_room',  // 云函数名称
      data: {  // 传给云函数的参数
        _id: room._id,
      },
      complete: res => {
        
        wx.navigateTo({
          url: '/pages/create_room/create_room',
          
        });
      }
    })

  },
  Bingo() {
    this.setData({
      is_end:'Modal3',
    })
  },
  game_over() {
    let room = this.data.room
    let user_data = this.data.user_data
    this.setData({
      is_end: 'Modal',
      show_message:'恭喜您 游戏胜利！'
    })
    if (room.room_state == undefined) room.room_state = false
    if(room.winner == undefined) room.winner = user_data.color 
    room.room_state = true
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'game_over',
      // 传给云函数的参数
      data: {
        _id: room._id,
        room_state: room.room_state,
       winner:room.winner
      },
      // 成功回调
      complete: res => {
        console.log(res)
      }
    })


  },
  cancel() {
    this.setData({
      is_end:'',
    })
  },
  room_end() {
    let room = this.data.room
    wx.cloud.callFunction({
      name: 'remove_room',  // 云函数名称
      data: {  // 传给云函数的参数
        _id: room._id,
      },
      complete: res => {
        wx.reLaunch({
          url: '/pages/index/index',
        });
      }
    })
  },
  create_tasks() {
  let tasks_center = []
  wx.cloud.callFunction({
    name: 'get_datas',  // 云函数名称
    data: {  // 传给云函数的参数
      name: 'task_center',
      filter: {}  //筛选条件，默认为空（即查询所有记录），格式 {key:'values'} 
    },
    complete: res => {
      tasks_center = res.result.data
      // console.log(tasks_center);
      let cnt = 0
      let array = new Array(104).fill(0)
      while (cnt<25){
        let idx = parseInt((Math.random() * 100));
        if (array[idx] == 0 && idx<96) {
          let temp = {}
          temp.color = 'white'
          temp.name = tasks_center[idx].tasks[0]
          tasks[cnt++] = temp
          array[idx] = 1
        }
      }
    }
  })
  },

})